import React, { useState } from "react";
import * as commonUtil from "../../../utils/commonUtil";
import * as customService from "../services/customService";

export function useCustomState() {

    const [loading, setLoading] = useState(false);
    const [focusBlurFlag, setFocusBlurFlag] = useState(false);
    const [completeStatus, setCompleteStatus] = useState("running");    // running：等待输入或运行中；finish：完成
    const [textChatMessages, setTextChatMessages] = useState([
        { id: commonUtil.generateUUID(), type: "ai", think: "", content: "你好！我是TaiXu智能，欢迎使用智能主题报告！" },
    ]);
    const [selectedPattern, setSelectedPattern,] = useState(null);
    const [workflowGraph, setWorkflowGraph] = useState(null);
    const [markdownTemplate, setMarkdownTemplate] = useState(
        `# 欢迎使用 Markdown 编辑器\n\n- 编辑左侧内容\n- 右侧实时预览\n\n\`\`\`js\nconsole.log('Hello, TaiXu-Admin!');\n\`\`\``
    );

    const onSendChat = (values, query) => {
        setLoading(true);
        textChatMessages.push({ id: commonUtil.generateUUID(), type: "user", think: "", content: query });
        const msgId = commonUtil.generateUUID();
        textChatMessages.push({ id: msgId, type: "ai", think: "", content: "正在思考中。。。。。。" });
        setTextChatMessages(textChatMessages);

        let params = { msgId, query: query, pattern: selectedPattern };
        customService.postTopicAgent(params).then(res => {
            if (res.code == 200) {
                const data = res.data?.chain_result;
                let newTextObj = textChatMessages.find(item => msgId == item.id);
                if (data.indexOf("<think>") > -1) {
                    newTextObj.think = newTextObj.think + res;
                }
                newTextObj.content = data;
                setTextChatMessages(textChatMessages);
                setLoading(false);
            }
        });
    }

    const loadWorkflowGraph = () => {
        const image_name = "Agent_Custom_Workflow.png";
        const image_path = "D:/Downloads/taixu/images/agentics/" + image_name;
        fetch('http://localhost:5000/common/download_image?image_path=' + image_path).then(res => res.blob()).then(res => {
            setWorkflowGraph(URL.createObjectURL(res));
        });
    }

    return {
        loading, setLoading,
        textChatMessages, setTextChatMessages,
        selectedPattern, setSelectedPattern,
        focusBlurFlag, setFocusBlurFlag,
        completeStatus, setCompleteStatus,
        workflowGraph, setWorkflowGraph,
        onSendChat, loadWorkflowGraph,
        markdownTemplate, setMarkdownTemplate
    };
}
